package com.intelli4.pos.ui;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

import com.intelli4.pos.controllers.SessionController;
import com.intelli4.pos.core.Operator;

public class WelcomeFrame extends JFrame {
	private static final long serialVersionUID = 3603595567741162988L;

	private SessionController sessionController;

	private JButton saleBtn;
	private JButton mgmtBtn;

	public WelcomeFrame() {
		super();

		init();
	}

	public void setSessionController(SessionController sessionController) {
		this.sessionController = sessionController;
	}

	protected void init() {
		setLayout(new BorderLayout());

		JPanel commandPanel = new JPanel(new FlowLayout());
		saleBtn = new JButton("Sale");
		saleBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				enterSaleScreen();
			}
		});
		commandPanel.add(saleBtn);

		mgmtBtn = new JButton("Management");
		mgmtBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				enterMgmtScreen();
			}
		});
		commandPanel.add(mgmtBtn);

		add(commandPanel, BorderLayout.SOUTH);
	}

	public void enterSaleScreen() {
		final AuthDialog dlg = new AuthDialog();
		dlg.setSize(400, 300);
		dlg.setVisible(true);
		dlg.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosed(WindowEvent e) {
				if (dlg.isAuthenticated()) {
					Operator operator = new Operator();
					try {
						sessionController.openNewSession(operator);
					} catch (Exception ex) {
						// oops
					}
					setVisible(false);
				}
			}
		});
	}

	public void enterMgmtScreen() {
		final AuthDialog dlg = new AuthDialog();
		dlg.setSize(400, 300);
		dlg.setVisible(true);
		dlg.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosed(WindowEvent e) {
				if (dlg.isAuthenticated()) {
					Operator operator = new Operator();
					try {
						sessionController.openNewSession(operator);
					} catch (Exception ex) {
						// oops
					}
					setVisible(false);
				}
			}
		});
	}

	public static void main(String[] args) {
		WelcomeFrame frame = new WelcomeFrame();
		frame.setSize(1024, 768);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
	}
}
